package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.train.service.IProjectAuthenPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 项目制兼职培训师积分控制器
 *
 * @author fengshuonan
 * @Date 2018-01-27 22:43:31
 */
@Controller
@RequestMapping("/projectAuthenPoints")
public class ProjectAuthenPointsController extends BaseController {

    private String PREFIX = "/train/projectAuthenPoints/";

    @Autowired
    private IProjectAuthenPointsService projectAuthenPointsService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;
    @Autowired
    private IEmployeeService employeeService;

    private static List<ProjectAuthenPoints> REPEAT = new ArrayList<>();

    /**
     * 跳转到项目制兼职培训师积分首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "projectAuthenPoints.html";
    }

    /**
     * 跳转到添加项目制兼职培训师积分
     */
    @RequestMapping("/projectAuthenPoints_add")
    public String projectAuthenPointsAdd(Model model) {
        model.addAttribute("authens", qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_PROJECT));
        return PREFIX + "projectAuthenPoints_add.html";
    }

    /**
     * 跳转到修改项目制兼职培训师积分
     */
    @RequestMapping("/projectAuthenPoints_update/{projectAuthenPointsId}")
    public String projectAuthenPointsUpdate(@PathVariable String projectAuthenPointsId, Model model) {
        ProjectAuthenPoints projectAuthenPoints = projectAuthenPointsService.selectById(projectAuthenPointsId);
        model.addAttribute("item",projectAuthenPoints);
        model.addAttribute("authens", qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_PROJECT));
        LogObjectHolder.me().set(projectAuthenPoints);
        return PREFIX + "projectAuthenPoints_edit.html";
    }

    /**
     * 获取项目制兼职培训师积分列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            List<ProjectAuthenPoints> projectAuthenPointss = projectAuthenPointsService.selectList(null);
            projectAuthenPointss.forEach(t -> {
                if(t.getStartDate() !=null){
                    t.setStrStartDate(Const.df.format(t.getStartDate()));
                }
                if(t.getEndDate() !=null){
                    t.setStrEndDate(Const.df.format(t.getEndDate()));
                }
            });
            return projectAuthenPointss;
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<ProjectAuthenPoints> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<ProjectAuthenPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            list= projectAuthenPointsService.selectList(nwWrapper);
        }

        list.forEach(t -> {
            if(t.getStartDate() !=null){
                t.setStrStartDate(Const.df.format(t.getStartDate()));
            }
            if(t.getEndDate() !=null){
                t.setStrEndDate(Const.df.format(t.getEndDate()));
            }
        });
        return list;
    }
    /**
     * 新增项目制兼职培训师积分
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ProjectAuthenPoints projectAuthenPoints) {
        projectAuthenPoints.setCreateDate(new Date());
        projectAuthenPoints.setDataOrigin(Const.IMPORT_TYPE_SYS);
        projectAuthenPointsService.insert(projectAuthenPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody ProjectAuthenPoints[] repeatData) {
        List<ProjectAuthenPoints> projectAuthenPointss = Arrays.asList(repeatData);
        Date now = new Date();
        List<QualityGradeRule> qualityGradeRules=qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_PROJECT);
        projectAuthenPointss.forEach(projectAuthenPoints -> {
            projectAuthenPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
            projectAuthenPoints.setCreateDate(now);
            String headSchoolHour = projectAuthenPoints.getHeadSchoolHour();
            Double hour = StringUtils.isEmpty(headSchoolHour) ? 0.0 : Double.valueOf(headSchoolHour);
            qualityGradeRules.forEach(item->{
                if(item.getGrade().equals(projectAuthenPoints.getTeachLevel())){
                    projectAuthenPoints.setTeachLevelCode(item.getGradeCode());
                    projectAuthenPoints.setIntegral(item.getIntegral() * hour);
                }
            });
        });
        projectAuthenPointsService.insertBatch(projectAuthenPointss);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除项目制兼职培训师积分
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String projectAuthenPointsId) {
        if(projectAuthenPointsId.contains(",")){
            List<String> ids = Arrays.asList(projectAuthenPointsId.split(","));
            projectAuthenPointsService.deleteBatchIds(ids);
        }else{
            projectAuthenPointsService.deleteById(projectAuthenPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改项目制兼职培训师积分
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ProjectAuthenPoints projectAuthenPoints) {
        projectAuthenPointsService.updateById(projectAuthenPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * 项目制兼职培训师积分详情
     */
    @RequestMapping(value = "/detail/{projectAuthenPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("projectAuthenPointsId") String projectAuthenPointsId) {
        return projectAuthenPointsService.selectById(projectAuthenPointsId);
    }


    /**
     * 跳转到导入项目制兼职培训师积分
     */
    @RequestMapping("/projectAuthenPoints_import")
    public String projectAuthenPointsImport() {
        return PREFIX + "projectAuthenPoints_import.html";
    }

    /**
     * 导入项目制兼职培训师积分
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);

        int count = 2;
        try {
            List<ProjectAuthenPoints> projectAuthenPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), ProjectAuthenPoints.class, params);
            Date now = new Date();
            List<QualityGradeRule> qualityGradeRules=qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_PROJECT);

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<ProjectAuthenPoints> noRepeat = new ArrayList<>();
            List<ProjectAuthenPoints> hasNameList = new ArrayList<>();

            for (ProjectAuthenPoints projectAuthenPoints : projectAuthenPointss) {
                projectAuthenPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                projectAuthenPoints.setCreateDate(now);
                String headSchoolHour = projectAuthenPoints.getHeadSchoolHour();
                Double hour = StringUtils.isEmpty(headSchoolHour) ? 0.0 : Double.valueOf(headSchoolHour);
                if(StringUtils.isEmpty(projectAuthenPoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(projectAuthenPoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(projectAuthenPoints.getEmpName()).contains(",")) {
                            //有重名情况
                            projectAuthenPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(projectAuthenPoints);
                        } else {
                            //无重名、正常插入
                            projectAuthenPoints.setEmpCode(nameAndCode.get(projectAuthenPoints.getEmpName()));

                            qualityGradeRules.forEach(item->{
                                if(item.getGrade().equals(projectAuthenPoints.getTeachLevel())){
                                    projectAuthenPoints.setTeachLevelCode(item.getGradeCode());
                                    projectAuthenPoints.setIntegral(item.getIntegral() * hour);
                                }
                            });

                            noRepeat.add(projectAuthenPoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + projectAuthenPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    qualityGradeRules.forEach(item->{
                        if(item.getGrade().equals(projectAuthenPoints.getTeachLevel())){
                            projectAuthenPoints.setTeachLevelCode(item.getGradeCode());
                            projectAuthenPoints.setIntegral(item.getIntegral() * hour);
                        }
                    });

                    hasNameList.add(projectAuthenPoints);
                }

                count++;
            }
            //不重复，先插入
            if(noRepeat.size() > 0){
                projectAuthenPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                projectAuthenPointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }
    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<ProjectAuthenPoints> projectAuthenPoints= projectAuthenPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("项目制兼职培训师积分统计表", "项目制兼职培训师积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ProjectAuthenPoints.class, projectAuthenPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="项目制兼职培训师积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
